package com.xiaolong.redis.handle;

import com.xiaolong.common.exception.BusinessException;
import com.xiaolong.common.utils.SpringUtil;
import com.xiaolong.redis.annotation.Lock;
import groovy.util.logging.Slf4j;
import jakarta.annotation.PostConstruct;
import org.aspectj.lang.ProceedingJoinPoint;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.DependsOn;

@Slf4j
@DependsOn("springUtil")
public class QueueLockHandler implements LockHandler {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    private RedissonClient redissonClient;

    @PostConstruct
    public void setRedissonClient() {
        this.redissonClient = SpringUtil.getBean(RedissonClient.class);
    }

    @Override
    public Object execute(ProceedingJoinPoint point, Lock lock) throws Throwable {
        //获取锁的key
        String key = lock.key();
        RLock redisLock = redissonClient.getLock(key);
        Object result = null;
        try {
            redisLock.lock();
            result = point.proceed();
        } finally {
            redisLock.unlock();
        }
        return result;
    }
}
